package com.bardsoftware.foronuvolo.server;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bardsoftware.foronuvolo.data.Discussion;
import com.bardsoftware.foronuvolo.data.DatastoreDiscussionChunk;
import com.bardsoftware.foronuvolo.data.Message;
import com.bardsoftware.foronuvolo.data.PMF;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskHandle;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class DeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        if (!req.getRequestURL().toString().startsWith(ForoNuvoloConstants.FORUM_DOMAIN)) {
            return;
        }
        UserService userService = UserServiceFactory.getUserService();

        String thisURL = req.getRequestURL().toString() + (req.getQueryString()!=null ? "?" + req.getQueryString() : "");
        if (req.getUserPrincipal() == null) {
            resp.sendRedirect(userService.createLoginURL(thisURL));
            return;
        }
        if (!userService.isUserAdmin()) {
            resp.sendRedirect(userService.createLogoutURL(thisURL));
            return;
        }
        doDelete(req);
        MessageCache.onDiscussionSetChange();
    }

    private void doDelete(HttpServletRequest req) {
        final String id = req.getParameter("id");
        if (id != null && !"".equals(id)) {
            final PersistenceManager pm = PMF.getFactory().getPersistenceManager();
            PMF.runInTransaction(pm, null, new Runnable() {
                public void run() {
                    Discussion d = Discussion.findByRefID(id);
                    if (d != null) {
                        pm.deletePersistent(d);
                    }
                }
            }, 3);
            pm.close();
            return;
        }
        if (DatastoreDiscussionChunk.deleteFirstPage()) {
            TaskOptions options = TaskOptions.Builder.url("/delete").method(TaskOptions.Method.GET);
            TaskHandle add = QueueFactory.getDefaultQueue().add(options);
        } else {
            Message.deleteAll();
        }
    }
}
